package com.offcn.service;

import com.offcn.dao.*;
import com.offcn.entity.Course;
import com.offcn.entity.Course_User;
import com.offcn.entity.User;
import com.offcn.utlis.PageUtils;

import java.util.List;

public class Course_UserServiceImpl  implements Course_UserService {
    // 调用dao层
   private    Course_UserDao course_userDao = new Course_UserDaoImpl();
   // 实例化 Userdao
   private UserDao userDao =new UserDaoImpl();
    // 实例化 CourseDao
    private CourseDao courseDao =new CourseDaoImpl();

    /**
     * 分页查询
     * @param currentPage
     * @param pageSize
     * @param search
     * @return
     */
    @Override
    public PageUtils<Course_User> findAll(int currentPage, int pageSize, String search) {
            // 查询总记录
            StringBuffer sb = new StringBuffer("select cu.* from course_user  as cu ,user as u where cu.uid = u.uid and  u.name like ?");
            List<Course_User> courseUsers = course_userDao.findAll(sb.toString(),"%" + search + "%" );
            int total = courseUsers == null? 0:courseUsers.size();
            // 分页
            sb.append(" limit ?, ? ");
            List<Course_User> courseUserList = course_userDao.findAll(sb.toString(),"%"+ search +"%",(currentPage-1)*pageSize,pageSize);
        for (Course_User courseUser : courseUserList) {
                // 从userdao的方法中 找出 uid 然后赋值给 user
               User user =   userDao.findByid(courseUser.getUid());
               // 从coursedao 找出 id 然后进行赋值
               Course course = courseDao.findAllByid(courseUser.getCid());
               // 赋值
                courseUser.setUser(user);
                courseUser.setCourse(course);
        }
        PageUtils<Course_User> pageUtils = new PageUtils<Course_User>(pageSize,currentPage,total,courseUserList);

            return pageUtils;
    }

    /**
     * 修改课程
     * @param cid
     * @param id
     * @return
     */
    @Override
    public boolean updateByid(int cid, int id) {
        return course_userDao.updateCourse(cid,id)>0;
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @Override
    public boolean deleteByid(String[] ids) {
        try {
            for (String id : ids) {
             int k  = course_userDao.deleteByid(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw  new RuntimeException();
        }
        return true;
    }


}
